// Copyright 2019 AI Redefined inc.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "easy_grpc/server/context.h"

namespace {
std::string_view slice_to_str(grpc_slice& slice) {
  auto start = slice.refcount ? slice.data.refcounted.bytes : slice.data.inlined.bytes;
  auto len = slice.refcount ? slice.data.refcounted.length : slice.data.inlined.length;

  return std::string_view(reinterpret_cast<const char*>(start), len);
}
}  // namespace
namespace easy_grpc {

std::string_view Context::get_client_header(std::string_view key) {
  grpc_metadata_array& metadata_array = call_.request_metadata_;

  auto key_as_slice = grpc_slice_from_static_buffer(key.data(), key.size());
  for (std::size_t i = 0; i < metadata_array.count; ++i) {
    if (grpc_slice_cmp(metadata_array.metadata[i].key, key_as_slice) == 0) {
      grpc_slice_unref(key_as_slice);

      return slice_to_str(metadata_array.metadata[i].value);
    }
  }

  grpc_slice_unref(key_as_slice);
  throw std::out_of_range("failed to lookup header");
}

}  // namespace easy_grpc